package com.eportal.action.background;

import com.eportal.action.BaseAction;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TAgent;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.SysmenuService;
import com.eportal.service.TAgentService;
import com.eportal.util.CityUtil;
import com.eportal.util.HomePageConfig;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合作方管理
 * @author chencheng
 *
 */
public class TAgentAction extends BaseAction implements ModelDriven<TAgent> {

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(TAgentAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();

    @Autowired
    private TAgentService tAgentService;
    @Autowired
    private SysmenuService resourceService;
	/**
     * 合作方管理
     */
    public String listView() {
        return SUCCESS;
    }

	/**
     * 合作方管理
     */
    public String accountListView() {
    	try{
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	getRequest().setAttribute("rLevel", user.getrLevel());
    		int userRole =  (Integer) getSession().getAttribute("userRole");
        	getRequest().setAttribute("userRole", userRole);
        	String homePageConfig = HomePageConfig.ZHANGHUGL;
        	String[] str = homePageConfig.split(",");
    		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    		getSession().setAttribute("mpid", Integer.parseInt(str[0]));
        	if(userRole == 1 || userRole == 2 || userRole == 21){
        		return "tagentlistView";
        	}else if(userRole == 3 || userRole == 4){
        		return "comuListView";
        	}else{
        		return "error";
        	}
    	}catch(Exception e){
    		log.error(this,e);
    		return "error";
    	}

    }

    /**
     * 合作方列表
     */
    public void page() throws Exception {
        JqGridPager page = new JqGridPager();
        String areaCode = getRequest().getParameter("areaCode");
    	String agtCode = getRequest().getParameter("agtCode");
    	String sysoptId = getRequest().getParameter("sysoptId");
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	if (StringUtils.isNotBlank(sysoptId)) {
    		where.append(" and t.sysoptId =");
			where.append(sysoptId);
		}else if (userRole == 21) {
			where.append(" and t.sysoptId =");
			where.append(user.getSid());
		}
    	if (StringUtils.isNotBlank(areaCode)) {
    		where.append(" and  substr(t.areaCode,1,");
        	if(CityUtil.isMunicipalities(areaCode)){//直辖市
        		where.append("2) = '");
        		where.append(areaCode.substring(0, 2));
        		where.append("'");
        	}else{
        		where.append("4) = '");
        		where.append(areaCode.substring(0, 4));
        		where.append("'");
        	}
        }
    	if (StringUtils.isNotBlank(agtCode)) {
            where.append(" and  t.agtCode = '");
            where.append(agtCode);
            where.append("'");
        }
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        List<TAgent> tAgents = tAgentService.list(page);
        jqGridQueryMap(TAgent.class, getRequest(), tAgents, getResponse(), page);
    }

    /**
     * 所有的合作方列表
     */
    public void list() throws Exception {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder("from TAgent where 1=1 ");
		//userRole 1:平台超级管理员  2:平台普通管理员  3:合作方超级管理员
    	if (userRole != 1 && userRole != 2 && userRole != 7 ) {  // 增加主板厂商 todo Updated by Saber on 2017/7/25 下午5:21
			if (userRole == 21) {
				where.append(" and sysoptId =");
				where.append(user.getSid());
			}else{
				where.append(" and agtCode ='");
				where.append(user.getAgtCode());
				where.append("'");
			}
			where.append(" and status = '1' ");
		}
    	List<TAgent> tAgents = tAgentService.list(where.toString());
        responseBody(tAgents);
    }

    /**
     * 合作方修改
     */
    public String editView() {
    	 String agtCode = getRequest().getParameter("agtCode");
    	StringBuffer sb = new StringBuffer("where t.agtCode='");
		sb.append(agtCode);
		sb.append("'");
    	List<Map<String, String>> list = tAgentService.getDeatil(sb.toString());
        getRequest().setAttribute("map", list.get(0));
        return SUCCESS;
    }

    /**
     * 合作方修改保存
     */
    public void update(){
    	TAgent tAgent = getModel();
    	result = tAgentService.updateMethod(tAgent);
        responseBody(result);
    }

    /**
     * 合作方修改资料保存
     */
    public void updateDetail(){
    	TAgent tAgent = getModel();
    	File file = getUpload();
    	String fileName = getUploadFileName();
    	result = tAgentService.tagentDetailMethod(tAgent,file,fileName);
        responseBody(result);
    }


    /**
     * 合作方注册
     */
    public String register() {
        return "register";
    }

    /**
     * 合作方注册
     */
    public String registerLock() {
        return "registerLock";
    }

    /**
     * 合作方注册
     */
	public void tagentAdd() throws IOException {
		TAgent tAgent = getModel();
		File file = getUpload();
		if(file!=null){
			boolean isImage = ValidateUtil.isImage(file);
			if (!isImage) {
				result.put("code", 0);
				result.put("msg", "文件的格式不正确");
				responseBody(result);
				return;
			}
		}

		String fileName = getUploadFileName();
		result = tAgentService.tagentAddMethod(tAgent, file, fileName);
		responseBody(result);
	}


    /**
     * 合作方删除
     */
    public void delete() {
    	String param_ids = getRequest().getParameter("ids");
    	result = tAgentService.deleteMethod(param_ids);
        responseBody(result);
    }

    /**
     * 审核合作方
     */
    public String auditListView() {
        return SUCCESS;
    }

    /**
     * 审核合作方
     * @throws Exception
     */
    public void auditList() throws Exception {
    	 JqGridPager page = new JqGridPager();
         setPage(getRequest(), page);
         page.setSord(null);
         page.setSidx(null);
         List<TAgent> tAgents = tAgentService.auditList(page);
         jqGridQueryMap(TAgent.class, getRequest(), tAgents, getResponse(), page);
    }

    /**
     * 合作方审核
     */
    public void audit(){
    	String sid = getRequest().getParameter("sid");
    	String status = getRequest().getParameter("status");
    	String comm = getRequest().getParameter("comm");
    	String sysoptId = getRequest().getParameter("sysoptId");
    	try {
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
    		result = tAgentService.auditMethod(sid,status,comm,sysoptId,user);
		} catch (MdKnownRunTimeException e) {
			log.error("公司审核失败",e);
			result.put("code", 0);
  	        result.put("msg", e.getMessage());
		}catch (Exception e) {
			log.error("公司审核失败",e);
			result.put("code", 0);
  	        result.put("msg", "公司审核失败");
		}
    	responseBody(result);
    }

    /**
     * 更改区域管理员
     * @return
     */
    public String editRegionView(){
    	String sid  = getRequest().getParameter("sid");
    	TAgent tAgent = tAgentService.get(Long.parseLong(sid));
    	if (tAgent != null) {
    		getRequest().setAttribute("agtName", tAgent.getAgtName());
    		getRequest().setAttribute("sysoptId", tAgent.getSysoptId());
    	}else{
    		return "error";
    	}
    	getRequest().setAttribute("sid", sid);
    	return SUCCESS;
    }

    /**
     *  更改区域管理员
     */
    public void editRegion(){
    	TAgent tAgent = getModel();
    	result = tAgentService.updateRegionManagerMethod(tAgent);
        responseBody(result);
    }

    /**
     * 审批通过指定区域管理员
     * @return
     */
    public String agree(){
    	String sid  = getRequest().getParameter("sid");
    	TAgent tAgent = tAgentService.get(Long.parseLong(sid));
    	if (tAgent != null) {
    		getRequest().setAttribute("agtName", tAgent.getAgtName());
		}else{
			return "error";
		}
    	getRequest().setAttribute("sid", sid);
    	getRequest().setAttribute("status", getRequest().getParameter("status"));
    	return SUCCESS;
    }
    /**
     * 审批拒绝原因填写
     * @return
     */
    public String refuse(){
    	getRequest().setAttribute("sid", getRequest().getParameter("sid"));
    	getRequest().setAttribute("status", getRequest().getParameter("status"));
    	return SUCCESS;
    }

    /**
     * 合作方修改
     */
    public String detailView() {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String agtCode = user.getAgtCode();
    	String mpid=getRequest().getParameter("mpid");
    	String homePageConfig = HomePageConfig.HEZUOFANGXX;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
		getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	if ("0".equals(agtCode)) {
    		return "error";
		}else{
			StringBuffer sb = new StringBuffer("where t.agtcode='");
			sb.append(agtCode);
			sb.append("'");
	    	List<Map<String, String>> list = tAgentService.getDeatil(sb.toString());
	        getRequest().setAttribute("map", list.get(0));
			return SUCCESS;
		}
    }



    /**
     * 平台报表详情页面
     * @return
     */
    public String pmsReportsView() {
    	String homePageConfig = HomePageConfig.PMSREPORTS;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	return "pmsReportsView";
    }

    /**
     * 平台报表详情数据
     * @throws Exception
     * @throws IOException
     */
    public void pmsReports() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	int userRole =  (Integer) getSession().getAttribute("userRole");
     	if (userRole != 1 && userRole != 2 && userRole != 21) {
     		return;
     	}
    	String agtCode = getRequest().getParameter("agtCode");
    	String tCommunityId = getRequest().getParameter("tCommunityId");
    	List<Map<String, String> > dataList = new ArrayList<Map<String, String> >();
    	if(StringUtils.isBlank(agtCode)){//全部
    		Sysopt user = (Sysopt) getSession().getAttribute("user");
    		dataList = tAgentService.getPmsReports(userRole,user);
    	}else if(StringUtils.isBlank(tCommunityId)){//合作方
    		dataList = tAgentService.tagentReports(agtCode);
    	}else{//社区报表
    		dataList = tAgentService.tcomuReports(agtCode,tCommunityId);
    	}
    	 jqGridQueryMap(Map.class, getRequest(), dataList, getResponse(), jqGridPager);
    }

    /**
     * 合作方报表详情
     * @return
     */
    public String tagentReportsView(){
    	String homePageConfig = HomePageConfig.TAGENTREPORTS;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	return SUCCESS;
    }

    /**
     * 合作方报表详情
     * @throws Exception
     * @throws IOException
     */
    public void tagentReports() throws Exception{
    	JqGridPager jqGridPager = new JqGridPager();
    	List<Map<String, String> > dataList = new ArrayList<Map<String, String> >();
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 5 || userRole == 6) {
    		return;
    	}
    	String agtCode = getRequest().getParameter("agtCode");

    	if(StringUtils.isBlank(agtCode)){
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	    agtCode = user.getAgtCode();
    	}
    	String tCommunityId = getRequest().getParameter("tCommunityId");
    	if(StringUtils.isBlank(tCommunityId)){//合作方
    		dataList = tAgentService.tagentReports(agtCode);
    	}else{//社区报表
    		dataList = tAgentService.tcomuReports(agtCode,tCommunityId);
    	}
    	jqGridQueryMap(Map.class, getRequest(), dataList, getResponse(), jqGridPager);
    }

    private TAgent tAgent = new TAgent();

    @Override
    public TAgent getModel() {
        return tAgent;
    }
}
